<template>
  <!-- 添加或修改订单产品工序分配任务对话框 -->
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <el-form ref="form" :model="form" label-width="120px">
      <el-tabs v-model="activeName" class="detail-tab" type="card">
        <el-tab-pane label="基本信息" name="first">
          <el-row :gutter="24">
            <!-- <el-col :span="12" v-for="(worker, index) in workers" :key="index" style="margin-top: 30px;">
              <el-form-item :label="'工人' + (index + 1)" :rules="{
               required: true, message: '不能为空', trigger: 'blur'
              }">
                <el-select v-model="worker.userId" :placeholder="'请选择工人'" filterable @change="selectUser" clearable>
                  <el-option v-for="dict in dict.type.sys_user" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
                <el-button type="danger" v-if="index!=0" @click="deleteWorker(index)">删除</el-button>
              </el-form-item>
            </el-col> -->

            <!-- <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="请输入总量" >
                <el-input-number v-model="sumRemainCount" @change="handleChangeSumCount()" :precision="0" :min="0" :max="this.sumRemainCountBfb"></el-input-number>
                <h style="color: red;">注：最大分配数量不可超出为百分比额</h>
              </el-form-item>
            </el-col> -->
            <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="请选择工人" >
                <el-cascader :options="options" :props="props" :placeholder="'请选择工人'" v-model="regionValue" @change="handleChangeRegion"
                  show-all-levels clearable></el-cascader>
              </el-form-item>
            </el-col>
             <el-col :span="8" style="margin-top: 30px;">
             <el-form-item label="派工日期:" prop="planStartTime">
              <el-date-picker clearable
                              v-model="form.planStartTime"
                              :default-value="currentDateTime"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择派工日期">
              </el-date-picker>
            </el-form-item>
            </el-col>

            <!--<el-form-item label="请购部门" prop="deptId" style="width: 500px">
              <treeselect :options="deptOptions" :show-count="true"  @select="selectDept" placeholder="请选择请购部门"
                          v-model="form.deptId"/>
            </el-form-item>
            <el-form-item label="请购人" prop="userId" style="width: 500px">
              <el-select v-model="form.userId" placeholder="请选择项目名称" filterable clearable style="width: 100%;">
                <el-option v-for="dict in userOptions" :key="dict.value"
                           :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>-->

            <!-- <el-col :span="12" style="margin-top: 30px;">
              <el-form-item label="">
                <el-button type="primary" @click="addWorker">继续添加工人</el-button>

              </el-form-item>
            </el-col> -->
          </el-row>
          <!--<el-col :span="12" style="margin-top: 30px;">
            <el-form-item label="分配数量" prop="count">
              <el-input-number v-model="form.count" :max="counts" @change="feipeiCount" placeholder="请输入分配数量"/>
            </el-form-item>
          </el-col>-->
        </el-tab-pane>
        <el-table border :data="columns" ref="table" row-key="id" v-loading="loading" :show-summary="false">
          <el-table-column align="center" label="序号" type="index" width="50">
            <template slot-scope="{ $index, row }">
              <span v-if="row.projectNo !== '合计'">{{ (queryParams.pageNum - 1) * queryParams.pageSize + $index }}</span>
              <span v-else>合计</span>
            </template>
          </el-table-column>
          <el-table-column label="订单编号" align="center" prop="projectNo" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span v-if="row.projectNo">{{ row.projectNo }}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品编码" align="center" prop="goodsCode">
            <template slot-scope="{ row }">
              <span v-if="row.goodsCode">{{ row.goodsCode }}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center" prop="goodsName" show-overflow-tooltip>
            <template slot-scope="{ row }">
              <span v-if="row.goodsName">{{ row.goodsName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="产品型号" align="center" prop="goodModel">
            <template slot-scope="{ row }">
              <span v-if="row.goodModel">{{ row.goodModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工艺名称" align="center" prop="gongyiName">
            <template slot-scope="{ row }">
              <span v-if="row.gongyiName">{{ row.gongyiName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工序名称" align="center" prop="name">
            <template slot-scope="{ row }">
              <span v-if="row.name">{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产名称" align="center" prop="gongxuName">
            <template slot-scope="{ row }">
              <span v-if="row.gongxuName">{{ row.gongxuName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="生产型号" align="center" prop="gongxuModel">
            <template slot-scope="{ row }">
              <span v-if="row.gongxuModel">{{ row.gongxuModel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="图纸号" align="center" prop="shuoming">
            <template slot-scope="{ row }">
              <span v-if="row.shuoming">{{ row.shuoming }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总数量" align="center" prop="counts">
            <template slot-scope="{ row }">
              <span v-if="row.counts">{{ row.counts }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已分配数量" align="center" prop="fenpeiCount">
            <template slot-scope="{ row }">
              <span v-if="row.fenpeiCount">{{ row.fenpeiCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分配数量" width="210" prop="goodSnum">
            <template slot-scope="{ row }">
              <el-input-number v-if="row.projectNo !== '合计'" v-model="row.goodSnum" :min="0" @change="() => handleChange(row)" :max="row.multiple ? 9999999 : Math.round(row.remainCount * sumRemainNumMsg)"></el-input-number>
              <span v-else>{{ row.goodSnum }}</span>
            </template>
          </el-table-column>
          <el-table-column label="乘倍数" width="210" prop="multiple">
            <template slot-scope="{ row }">
              <el-input-number v-if="row.projectNo !== '合计'" v-model="row.multiple" :min="0" @change="() => multipleChange(row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="剩余分配数量" align="center" prop="remainCount">
            <template slot-scope="{ row }">
              <span v-if="row.remainCount">{{ row.remainCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="已完成数量" align="center" prop="finishCount">
            <template slot-scope="{ row }">
              <span v-if="row.finishCount">{{ row.finishCount }}</span>
            </template>
          </el-table-column>
          <el-table-column label="剩余完成数量" align="center" prop="remainfinishCount">
            <template slot-scope="{ row }">
              <span v-if="row.remainfinishCount">{{ row.remainfinishCount }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="备注" prop="remark">
            <template slot-scope="{ row }">
              <span v-if="row.remark">{{ row.remark }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-tabs>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定 分 配</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addAction, getById, updateAction, getAction, accAdd } from '@/api/manage';
import moment from 'moment';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { treeselect } from "@/api/system/dept";

export default {
  name: "PiliangPaigongForm",
  dicts: ['sys_user'],
  components: {
    Treeselect,
  },
  data() {
    return {
      regionValue: [],
      props: {
        multiple: true,
        emitPath: false,
        value: 'id',
        label: 'label',
        children: 'children'
      },
      options: [],
      // 遮罩层
      loading: true,
      activeName: "first",
      // 弹出层标题
      title: "",
      deptOptions: [],
      userOptions: [],
      // 是否显示弹出层
      open: false,
      parentId: null,
      counts: null,
      sumRemainCount: 0,
      sumRemainCountOld: 0,
      sumRemainCountBfb: 0,
      sumRemainNumMsg:0,
      baifenbi: 1,
      // 表单参数
      form: {
         planStartTime:null
      },
      columns: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params: {},
        id: null,
        code: null,
      },
      queryParamsUser: {
        pageNum: 1,
        pageSize: 1000,
        deptId: null,
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "工人不能为空", trigger: "blur" }
        ],
      },
      url: {
        getById: '/goodsSaledoGongxuUser/goodsSaledoGongxuUser/',
        addUserTaskPiliang: '/goodsSaledoGongxuUser/goodsSaledoGongxuUser/addUserTaskPiliang',
        edit: '/goodsSaledoGongxuUser/goodsSaledoGongxuUser/edit',
        getUserByDept: '/system/user/getUserByDept',
        getAllShpper: '/system/dept/treeselect',
        getConsumer: '/system/user/getUserByDept',
        userTreeSelect: '/system/dept/userTreeSelect'
      },
      workers: [{ userId: null }], // 新增的工人选择下拉框数组
    };
  },
  created() {
    this.getTreeselect();
    this.getUser();
  },
  computed: {
    currentDateTime() {
       this.form.planStartTime = new Date()
      return new Date();
    }
  },
  methods: {
    handleChangeSumCount() {
      this.columns.forEach(item => {
        item.goodSnum = Math.round(item.remainCount * (this.sumRemainCount / this.sumRemainCountOld));
      });
      this.addSummaryRow();
    },
    handleChange(row) {
      const index = this.columns.findIndex(item => item.id === row.id);
      if (index > -1) {
        this.columns[index] = row;
        this.addSummaryRow();
      }
    },
    multipleChange(row) {
       const index = this.columns.findIndex(item => item.id === row.id);
      if (index > -1) {
        this.columns[index].goodSnum = row.multiple * this.columns[index].counts;
        this.addSummaryRow();
      }
    },
    handleChangess(value) {
      console.log(value.$index, value.row.goodSnumsss, '这是什么玩意');
      this.columns[value.$index].goodSnum = this.columns[value.$index].remainCount * value.row.goodSnumsss;
      this.columns = JSON.parse(JSON.stringify(this.columns));
      this.addSummaryRow();
    },
    addSummaryRow() {
      const summaryIndex = this.columns.findIndex(row => row.projectNo === '合计');
      if (summaryIndex > -1) {
        this.columns.splice(summaryIndex, 1);
      }
      const summary = {
        projectNo: '合计',
        goodsCode: '',
        goodsName: '',
        goodModel: '',
        gongyiName: '',
        code: '',
        name: '',
        shuoming: '',
        multiple:'',
        counts: this.columns.reduce((sum, item) => sum + (item.counts || 0), 0),
        fenpeiCount: this.columns.reduce((sum, item) => sum + (item.fenpeiCount || 0), 0),
        goodSnum: this.columns.reduce((sum, item) => sum + (item.goodSnum || 0), 0),
        remainCount: this.columns.reduce((sum, item) => sum + (item.remainCount || 0), 0),
        finishCount: this.columns.reduce((sum, item) => sum + (item.finishCount || 0), 0),
        remainfinishCount: this.columns.reduce((sum, item) => sum + (item.remainfinishCount || 0), 0),
        money: this.columns.reduce((sum, item) => sum + (item.money || 0), 0),
        goodHour: this.columns.reduce((sum, item) => sum + (item.goodHour || 0), 0),
        remark: ''
      };
      this.columns.unshift(summary);
      this.$refs.table.doLayout();
    },
    handleChangeRegion(e) {
      // console.log(e,'这是什么玩意');
      // console.log(this.regionValue,'这是什么玩意');
    },
    getUser() {
      let that = this;
      getAction(that.url.userTreeSelect, { parentId: '57d779853f0f4d14b03d51db30099456' }).then(res => {
        that.options = res.data;
        that.options.map((item) => {
          item = {
            value: item.id,
            label: item.label,
            children: item.children ? item.children.map(child => ({
              value: child.id,
              label: child.label
            })) : []
          }
        });
      })
    },

   /* selectUser(value) {
      let that = this;
      if (value && value.length > 0) {
        value.forEach((userId, index) => {
          const user = that.dict.type.sys_user.find(user => user.value === userId);
          if (user) {
            that.workers[index] = { userId: user.value, userName: user.label };
          }
        });
      } else {
        that.workers = [{ userId: null }];
      }
    },*/

    initUser() {
      let that = this;
      getAction(that.url.getUserByDept, this.queryParamsUser).then(res => {
        that.userOptions = res.data.nameList;
      })
    },
    selectDept(e) {
      let that = this;
      that.$set(that.form, "deptName", e.label);
      this.queryParamsUser.deptId = e.id;
      this.initUser();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
   /* selectUser(value) {
      let that = this;
      that.$nextTick(() => {
        let arr = that.$refs.myselectUser;
        for (let i = 0; i < arr.length; i++) {
          if (arr[i].currentValue == value) {
            that.form.userName = arr[i].label;
          }
        }
      })
    },*/
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        xuhao: null,
        code: null,
        name: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        shuoming: null,
        status: "0",
        projectId: null,
        projectCode: null,
        projectName: null,
        saleId: null,
        goodsId: null,
        gongyiId: null,
        gongxuId: null,
        gongyiCode: null,
        goodsCode: null,
        goodsName: null,
        goodsModel: null,
        goodsBrand: null,
        doStartTime: null,
        doEndTime: null,
        planStartTime: null,
        planEndTime: null,
        userId: null,
        userName: null,
        money: null,
        count: null,
        allMoney: null,
        remainCount: null,
        parentId: null,
      };
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    piliangFenpeiGxpShow(selectRows) {
      let that = this;
      that.reset();
      that.getConfigKey("baifenbi").then(response => {
        that.columns = selectRows;
        let sum = 0;
        that.columns.forEach(item => {
          item.goodSnum = item.remainCount;
          sum += item.goodSnum;
        });
        that.sumRemainNumMsg= response.msg;
        that.sumRemainCount = sum;
        that.sumRemainCountOld = sum;
        that.sumRemainCountBfb = that.sumRemainCountOld * response.msg;
        this.addSummaryRow();
      });
      that.open = true;
      that.loading = false;
      that.title = "批量分配订单1产品工序任务";
    },
    feipeiCount() {
      let that = this;
      if (that.form.money && that.form.count) {
        let totlePrice = this.functionNumberMul(that.form.count, that.form.money);
        that.$set(that.form, "allMoney", totlePrice);
      }
    },
    functionNumberMul(arg1, arg2) {
      var m = 0;
      var s1 = arg1.toString();
      var s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length;
      } catch (e) {
      }
      try {
        m += s2.split(".")[1].length;
      } catch (e) {
      }
      return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getById(this.url.getById, id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单产品工序分配任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let that = this;
      console.log(this.workers)
      let userIdres = '';
      // for (let i = 0; i < that.workers.length; i++) {
      //   if (that.workers[i].userId) {
      //     userIdres += that.workers[i].userId + ',';
      //   }
      // }
      for (let i = 0; i < that.regionValue.length; i++) {
        if (that.regionValue[i]) {
          userIdres += that.regionValue[i] + ',';
        }
      }
      if (userIdres == '') {
        that.$modal.msgError("请选择工人");
        return;
      }
      const goodsOrderIn = Object.assign({});
      goodsOrderIn.userIds = userIdres;
      // goodsOrderIn.userName = that.form.userName;
      //goodsOrderIn.form = that.form;
      goodsOrderIn.columnsGongxu = that.columns;
      goodsOrderIn.columnsGongxu.shift()
      goodsOrderIn.columnsGongxu.forEach(item => {
        item.remainCount = item.goodSnum
        item.type = '0';
      });
      addAction(that.url.addUserTaskPiliang, goodsOrderIn).then(response => {
        that.open = false;
        that.$modal.msgSuccess("选择成功！");
        that.$emit('ok');
        //that.getList2();
        that.handleQuery();
      });
    },
    addWorker() { // 新增的方法，用于动态添加工人选择下拉框
      this.workers.push({ userId: null });
    },
    deleteWorker(index) {
      this.workers.splice(index, 1);
    }
  }
};
</script>
